package com.joezhou.jdbc.v2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据源类：驱动，获取连接，关闭连接
 *
 * 添加连接池功能
 *
 * @author JoeZhou
 */
public class DataSource {

    private static List<Connection> connectionPool = new ArrayList<>();
    private static String driver = "com.mysql.cj.jdbc.Driver";
    private static String url = "jdbc:mysql://localhost:3306/j2102?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8";
    private static String username = "joezhou";
    private static String password = "joezhou";

    static {
        try {
            Class.forName(driver);

            // 循环创建10个连接，并加入连接池
            for (int i = 0; i < 10; i++) {
                connectionPool.add(DriverManager.getConnection(url, username, password));
            }


        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回连接
     */
    public Connection getConnection() {
        Connection result = null;
        try {
            if (connectionPool.isEmpty()) {
                // 创建一个新的连接并返回
                result = DriverManager.getConnection(url, username, password);
            } else {
                // 从连接池中获取一个连接并返回
                // remove(0)，表示返回并删除列表中的第0个元素
                result = connectionPool.remove(0);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 关闭连接
     */
    public void closeConnection(Connection connection) {
        try {
            if (connection != null) {
                // 连接池满了，没有空余位置
                if(connectionPool.size() == 10){
                    connection.close();
                }else{
                    connectionPool.add(connection);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
